<template>
  <div class="edit-class-modal modal">
    <div class="edit-class">
      <div class="header">{{ classItem.Name }}</div>
      <div class="body">
        <template v-if="showTable">
          <div class="nav-wrapper">
            <div
              class="nav-item btn"
              :class="{ current: nav.id === item.id }"
              v-for="item in navList"
              :key="item.id"
              @click="nav = item"
            >
              {{ item.name }}
            </div>
          </div>
          <div class="content-wrapper" v-loading="loading">
            <!-- 编辑当前班级 -->
            <div class="class-content" v-if="nav.id === 0">
              <div class="row">
                <span class="label">
                  <i class="red">*</i>
                  年级：</span
                >
                <el-select v-model="classItem.GradeId">
                  <el-option
                    v-for="{ id, name } in schoolGradeList"
                    :key="id"
                    :value="id"
                    :label="name"
                  >
                  </el-option>
                </el-select>
              </div>
              <div class="row">
                <div>
                  <span class="label">
                    <i class="red">*</i>
                    班级名称：</span
                  >
                  <el-input
                    v-model="classItem.localClassName"
                    maxlength="10"
                    show-word-limit
                  ></el-input>
                </div>
                <div class="name-desc">显示为: {{ computedName }}</div>
              </div>
              <div class="row">
                <span class="label">
                  <i class="red">*</i>
                  班级排序：</span
                >
                <el-input v-model="classItem.Sort"></el-input>
              </div>
            </div>
            <!-- 教师表格 -->
            <div class="teacher-content" v-else-if="nav.id === 1">
              <el-table :data="teachers">
                <el-table-column
                  label="科目"
                  prop="F_subject_name"
                  align="center"
                >
                </el-table-column>
                <el-table-column label="老师姓名" prop="F_name" align="center">
                </el-table-column>
                <el-table-column label="手机号" prop="F_phone" align="center">
                </el-table-column>
                <el-table-column
                  label="班主任"
                  prop=""
                  align="center"
                  width="80"
                >
                  <template #default="scope">
                    <span>{{ scope.row.F_master === 1 ? '是' : '否' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" prop="" align="center">
                  <template #default="scope">
                    <span class="btn" @click="deleteTeacher(scope.row)"
                      >删除</span
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- 学生表格 -->
            <div class="student-content" v-else>
              <el-table :data="students">
                <el-table-column
                  label="学号/考号"
                  prop="F_no"
                  min-width="140"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  label="学生姓名"
                  prop="F_name"
                  min-width="140"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  label="学生账号"
                  prop="F_account"
                  align="center"
                  min-width="140"
                >
                </el-table-column>
                <el-table-column
                  label="性别"
                  prop="F_gender"
                  align="center"
                  min-width="140"
                >
                </el-table-column>
                <el-table-column
                  label="家长电话"
                  prop="F_phone"
                  min-width="140"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  label="选考科目"
                  v-if="classItem.GradeId >= 10"
                  align="center"
                  min-width="140"
                >
                  <template #default="scope">
                    <span>{{ getSubjectNameStr(scope.row.courses) }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </template>
        <template v-else>
          <div class="content-wrapper">
            <!-- 添加教师 -->
            <add-teacher v-if="nav.id === 1" ref="addTeacher"></add-teacher>
            <!-- 添加学生 -->
            <add-student
              v-else
              ref="addStudent"
              :classItem="classItem"
            ></add-student>
          </div>
        </template>
      </div>
      <div class="footer">
        <div class="btn-group">
          <div class="cancel-btn btn" @click="cancel()">关闭</div>
          <div class="add-teacher-btn btn" @click="add()" v-if="nav.id === 0">
            确认
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import AddTeacher from './addTeacher.vue';
import AddStudent from './addStudent.vue';
import { mapGetters } from 'vuex';
export default {
  name: '',
  components: {
    AddTeacher,
    AddStudent,
  },
  props: {
    classId: { type: String, required: true },
  },
  data() {
    return {
      loading: true,
      navList: [
        { name: '班级信息', id: 0 },
        { name: '老师信息', id: 1 },
        { name: '学生信息', id: 2 },
      ],
      nav: { name: '班级信息', id: 0 },
      teacher: {},
      teachers: [],
      students: [],
      showTable: true,
      newTeacher: {},
      newStudent: {},
      showDeleteTeacher: false,

      classItem: {},
      classSort: 0,
    };
  },
  computed: {
    ...mapGetters('school', [
      'schoolId',
      'schoolSubjectList',
      'schoolGradeList',
    ]),
    confirmBtnText() {
      const { id } = this.nav;
      return id === 0 ? '确认' : id === 1 ? '添加老师' : '添加学生';
    },
    computedName() {
      const gradeName =
        this.schoolGradeList.find((e) => e.id === this.classItem.GradeId)
          ?.name || '';
      const { localClassName } = this.classItem;
      if (Number(localClassName) == localClassName) {
        return `${gradeName}（${localClassName}）班`;
      } else {
        return `${gradeName}${localClassName}班`;
      }
    },
  },
  mounted() {
    this.getClassInfo();
  },
  watch: {},
  methods: {
    getSubjectNameStr(courses) {
      if (courses === undefined) return '';
      courses = courses === '' ? [] : JSON.parse(courses);
      const list = this.schoolSubjectList.filter((e) => courses.includes(e.id));
      return ['语文', '数学'].concat(list.map((e) => e.name)).join('、');
    },
    async getClassInfo() {
      const { F_teachers, F_students, F_class } = await this.$api.getClass({
        F_school_id: this.schoolId,
        F_class_id: this.classId,
      });
      this.teachers = F_teachers || [];
      this.students = F_students || [];
      this.teachers.forEach((e) => {
        const subjectId = e.F_subject;
        e.F_subject_name =
          this.schoolSubjectList.find((e) => e.id === subjectId)?.name || '-';
      });

      // 班级信息
      this.classItem = F_class;
      const { ClassIndex, ClassIndex2 } = this.classItem;
      const name = ClassIndex !== 0 ? ClassIndex : ClassIndex2;
      // Vue 3 中不再需要 $set，直接赋值即可
      this.classItem.localClassName = name;

      this.loading = false;
    },
    deleteTeacher(item) {
      this.$delete(item.F_name, async () => {
        try {
          const { F_responseNo, F_responseMsg } = await this.$api.deleteTeacher(
            {
              F_school_id: this.schoolId,
              F_teacher_id: item.F_id,
            }
          );
          if (F_responseNo === 10000) {
            this.$toast('删除该老师成功');
            await this.getClassInfo();
          } else this.$toast(`删除该老师失败:${F_responseMsg}`);
        } catch (e) {
          console.error(e);
          this.$toast('删除该老师失败');
        }
      });
    },
    async add() {
      if (this.nav.id === 0) {
        this.editClass();
      } else {
        if (this.showTable === true) {
          this.showTable = false;
        } else {
          if (this.nav.id === 1) {
            this.confrimAddTeacher();
          } else {
            this.confrimAddStudent();
          }
        }
      }
    },
    async confrimAddTeacher() {
      const teacher = this.$refs.addTeacher.newTeacher;
      const formData = new FormData();
      const params = {
        F_school_id: this.schoolId,
        F_teach_list: JSON.stringify([
          {
            F_class_id: this.classItem.Id,
            F_grade_id: this.classItem.GradeId,
            F_subject_id: teacher.F_subject,
          },
        ]),
        F_manage_list: JSON.stringify(
          teacher.F_master ? [{ F_class_id: this.classItem.Id }] : []
        ),
        ...teacher,
      };
      for (let [k, v] of Object.entries(params)) {
        formData.append(k, v);
      }
      try {
        const { F_responseMsg, F_responseNo } = await this.$api.addTeacher(
          formData
        );
        if (F_responseNo === 10000) {
          this.$toast('添加老师成功');
          await this.getClassInfo();
          this.showTable = true;
        } else {
          this.$toast(F_responseMsg);
        }
      } catch (e) {
        console.error(e);
        this.$toast('添加老师失败');
        return;
      }
    },
    async confrimAddStudent() {
      const formData = new FormData();
      const { newStudent, language, courseType, checkedSubject } =
        this.$refs.addStudent;
      if (checkedSubject.length !== 2) {
        this.$toast('选考科目请4选2');
        return;
      }
      newStudent.courses = JSON.stringify(
        [].concat(language).concat(courseType).concat(checkedSubject)
      );
      const params = {
        ...newStudent,
        F_school_id: this.schoolId,
        F_class_id: this.classItem.Id,
      };
      for (let [k, v] of Object.entries(params)) {
        formData.append(k, v);
      }
      try {
        const { F_responseMsg, F_responseNo } = await this.$api.addStudent(
          formData
        );
        if (F_responseNo === 10000) {
          this.$toast('添加学生成功');
          await this.getClassInfo();
          this.showTable = true;
        } else this.$toast(F_responseMsg);
      } catch (e) {
        console.error(e);
        this.$toast('添加学生失败');
        return;
      }
    },
    async editClass() {
      const { GradeId, localClassName, Sort } = this.classItem;
      const params = {
        F_school_id: this.schoolId,
        F_grade_id: GradeId,
        F_class_id: this.classItem.Id,
        F_class_name: localClassName,
        F_class_sort: Sort,
      };
      const formData = new FormData();
      for (let [k, v] of Object.entries(params)) {
        formData.append(k, v);
      }
      const { F_responseNo, F_responseMsg } = await this.$api.editClass(
        formData
      );
      if (F_responseNo === 10000) {
        this.$toast('编辑班级成功');
        this.$emit('update');
      } else {
        this.$toast(F_responseMsg);
      }
    },
    cancel() {
      if (!this.showTable) {
        this.showTable = true;
      } else {
        this.$emit('cancel');
      }
    },
  },
};
</script>

<style lang="less" scoped>
.edit-class {
  box-sizing: border-box;
  width: 900px;
  max-height: 496px;
  border-radius: 6px;
  background-color: #fff;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  display: flex;
  flex-direction: column;
  .header {
    height: 60px;
    line-height: 60px;
  }
  .body {
    height: calc(100% - 120px);
    display: flex;
    flex-direction: column;
    .nav-wrapper {
      width: 100%;
      display: flex;
      background-color: #f4f4f4;
      .nav-item {
        height: 35px;
        line-height: 35px;
        width: 100px;
      }
      .btn {
        border-radius: 0;
      }
      .current {
        background-color: #009cff;
        color: #fff;
      }
    }
    .content-wrapper {
      flex: auto;
      overflow-x: auto;
      span.btn {
        &:hover {
          color: #009cff;
        }
      }
    }
    .class-content {
      box-sizing: border-box;
      width: 100%;
      height: 100%;
      padding: 50px 120px;
      text-align: left;
      .row {
        margin-bottom: 20px;
        &:last-child {
          margin: 0;
        }
        .label {
          display: inline-block;
          width: 100px;
          text-align: right;
        }
        .name-desc {
          font-size: 12px;
          padding: 5px 0 0 102px;
          color: #8c8c8c;
        }
      }
      .el-input {
        width: 230px;
      }
    }
  }
  .red {
    font-style: normal;
    color: #f56c6c;
  }

  .footer {
    height: 60px;
    .btn-group {
      height: 60px;
      display: flex;
      justify-content: center;
      align-items: center;
      .btn {
        width: 90px;
        height: 35px;
        line-height: 35px;
      }
      .cancel-btn {
        background-color: #ffffff;
        color: #787777;
        border: solid 1px #d3d2d2;
        margin-right: 20px;
      }
      .add-teacher-btn {
        background-color: #009cff;
        color: #fff;
      }
    }
  }
}
</style>
